package com.shujia.flink.core

import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.time.Time

object Demo5EventTIme {
  def main(args: Array[String]): Unit = {


    /*
001,1647676561000
001,1647676562000
001,1647676563000
001,1647676565000
001,1647676564000
001,1647676566000
001,1647676567000
001,1647676568000
001,1647676569000
001,1647676570000
001,1647676575000
     */

    /**
      * 使用事件事件划分窗口
      * 1、设置事件模式为事件时间
      * 2、指定时间字段
      */


    /**
      * 每隔5秒统计用户出现的次数
      *
      */

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    env.setParallelism(1)

    //设置时间模式
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)


    val linesDS: DataStream[String] = env.socketTextStream("master", 8888)


    val eventDS: DataStream[(String, Long)] = linesDS.map(line => {
      val split: Array[String] = line.split(",")
      (split(0), split(1).toLong)
    })

    //设置时间字段， 水位线默认等于最新数据的时间戳，水位线只增加不减少
    //    val assDS: DataStream[(String, Long)] = eventDS.assignAscendingTimestamps(_._2)


    //设置水位线和时间字段
    val assDS: DataStream[(String, Long)] = eventDS.assignTimestampsAndWatermarks(
      //执行水位线前移的时间
      new BoundedOutOfOrdernessTimestampExtractor[(String, Long)](Time.seconds(5)) {
        //指定时间戳字段
        override def extractTimestamp(element: (String, Long)): Long = element._2
      }
    )

    /**
      * 事件时间窗口触发条件
      * 1、窗口内有数据
      * 2、最新数据的时间大于等于窗口的结束数据
      *
      */

    val countDS: DataStream[(String, Int)] = assDS
      .map(kv => (kv._1, 1))
      .keyBy(_._1)
      .timeWindow(Time.seconds(5))
      .sum(1)

    countDS.print()

    env.execute()


  }

}
